﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Framework.Model;
using Ninject;

namespace MvcApplication1.Controllers
{
    public class QueryController : Controller
    {
        [Inject]
        public Repository Repository { get; set; }

        private static readonly Dictionary<string, Type> PersistentTypesByName = GetPersistentTypes();

        private static Dictionary<string, Type> GetPersistentTypes()
        {
            return typeof (QueryController)
                .Assembly
                .GetTypes()
                .Where(t => typeof (IId).IsAssignableFrom(t))
                .ToDictionary(t => t.Name);
        }

        public ActionResult Count(string target)
        {
            try
            {
                var queryType = PersistentTypesByName[target];
                return Json(new {Success = true, Result = Repository.Count(queryType)});
            }
            catch (Exception e)
            {
                return Json(new {Success = false, Error = e.Message});
            }
        }

        public ActionResult Query(Query query)
        {
            try
            {
                var queryType = PersistentTypesByName[query.Target];

                var result = Repository
                    .Find(queryType, null, query.PageNumber, query.PageCount,
                          query.Sort ?? new[] {new SortColumn {Column = "Id", Order = "desc"}})
                    .Cast<object>()
                    .Select(o => new {Object = o, Type = o.GetType().Name});

                return Json(new {Success = true, Result = result});
            }
            catch (Exception e)
            {
                return Json(new {Success = false, Error = e.Message});
            }
        }
    }
}